<template>
    <el-container class="bg-white">
        <el-header class="sticky top-0 z-10 w-full">
            <!-- 固钉组件，固钉到顶部 -->
            <el-affix :offset="20" style="width: 100%; margin-bottom: 20px">
                <!-- 指定 flex 布局， 高度为 10， 背景色为白色 -->
                <div class="flex h-10 bg-white items-center">
                    <div class="mr-auto flex">
                        <el-button @click="exitEdit" type="warning">
                            <el-icon class="ml-1">
                                <ArrowLeft />
                            </el-icon>
                            文章管理
                        </el-button>
                    </div>
                    <!-- 字体加粗 -->
                    <h1 class="font-bold" style="justify-items: center; font-size: 20px;">写文章</h1>
                    <!-- 靠右对齐 -->
                    <div class="ml-auto flex">
                        <el-button type="primary" @click="publishArticleSubmit">
                            <el-icon class="mr-1">
                                <Promotion />
                            </el-icon>
                            发布文章
                        </el-button>
                    </div>
                </div>
            </el-affix>
        </el-header>
        <el-main>
            <div style="margin-top: 10px;">
                <!-- label-position="top" 用于指定 label 元素在上面 -->
                <el-form :model="form" ref="publishArticleFormRef" label-position="top" size="large" :rules="rules">
                    <el-form-item label="标题" prop="title">
                        <el-input v-model="form.title" autocomplete="off" size="large" maxlength="52" show-word-limit
                            clearable />
                    </el-form-item>
                    <el-form-item label="内容" prop="content">
                        <!-- Markdown 编辑器 -->
                        <MdEditor v-model="form.content" editorId="publishArticleEditor" :previewTheme="mdPreviewTheme"
                            @onUploadImg="onUploadImg" @onSave="onSave" :toolbars="toolbars" htmlPreview="true"
                            abWidth="4" autoDetectCode="true">
                            <template #defToolbars>
                                <Emoji>
                                    <template #trigger> Emoji </template>
                                </Emoji>
                                <Mark>
                                    <template #trigger> mark </template>
                                </Mark>
                                <ExportPDF :modelValue="form.content" @onProgress="handleProgress" :fileName="form.title" />
                            </template>
                        </MdEditor>
                    </el-form-item>
                    <el-form-item label="封面" prop="cover">
                        <el-upload class="avatar-uploader" action="#" :auto-upload="false" :show-file-list="false"
                            :on-change="handleCoverChange">
                            <img v-if="form.cover" :src="form.cover" class="avatar" />
                            <el-icon v-else class="avatar-uploader-icon">
                                <Plus />
                            </el-icon>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="摘要" prop="summary">
                        <!-- :rows="3" 指定 textarea 默认显示 3 行 -->
                        <el-input v-model="form.summary" :rows="3" type="textarea" placeholder="请输入文章摘要" />
                    </el-form-item>
                    <el-form-item label="分类" prop="categoryId">
                        <el-select v-model="form.categoryId" clearable placeholder="---请选择---" size="large"
                            style="width: 200px;">
                            <el-option v-for="item in categories" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="标签" prop="tags">
                        <!-- 标签选择 -->
                        <el-select v-model="form.tags" multiple filterable remote reserve-keyword
                            placeholder="---请输入---" remote-show-suffix :remote-method="remoteMethod" allow-create
                            default-first-option :loading="tagSelectLoading" size="large" style="width: 640px;"
                            tag-type="success">
                            <el-option v-for="item in tags" :key="item.value" :label="item.label" :value="item.value" />
                        </el-select>
                    </el-form-item>
                </el-form>
            </div>
        </el-main>
    </el-container>
</template>

<script setup>
import { ref, reactive, nextTick, watch, onMounted, onBeforeUnmount } from 'vue';
import { publishArticle, getArticlePageList, deleteArticle, viewArticle, updateArticle, autoSaveArticle } from '@/api/admin/article';
import { showMessage, showModel } from '@/composables/utils';
// 引入md - editor - v3编辑器
import { MdEditor, config } from 'md-editor-v3';
import 'md-editor-v3/lib/style.css'
import { uploadFile } from '@/api/admin/file';
import { getCategoryList } from '@/api/admin/category';
import { getTagSelectList, searchLikeTagName } from '@/api/admin/tag';
import { useRouter } from 'vue-router';
import { getArticleId, removeArticleId, setArticleId } from '@/composables/article';
import { Emoji } from '@vavt/v3-extension';
import { ExportPDF } from '@vavt/v3-extension';
import '@vavt/v3-extension/lib/asset/style.css';
// 引入公共库中的预览主题
import '@vavt/cm-extension/dist/previewTheme/arknights.css';
import { Mark } from '@vavt/v3-extension';
import MarkExtension from 'markdown-it-mark';

config({
  markdownItConfig(md) {
    md.use(MarkExtension);
  }
});

const handleProgress = (progress) => {
  console.log(`Export progress: ${progress.ratio * 100}%`);
};
//路由
const router = useRouter()
// md编辑器预览样式
const mdPreviewTheme = ref("smart-blue")
const toolbars = ref([
    'bold',
    'underline',
    'italic',
    '-',
    'title',
    'strikeThrough',
    'sub',
    'sup',
    'quote',
    'unorderedList',
    'orderedList',
    'task',
    '-',
    'codeRow',
    'code',
    'link',
    'image',
    'table',
    'mermaid',
    'katex',
    '-',
    'revoke',
    'next',
    'save',
    '-',
    '0',
    '1',
    '-',
    '2',
    '=',
    'pageFullscreen',
    'fullscreen',
    'preview',
    'previewOnly',
    'htmlPreview',
    'catalog',
    'github'
])
//添加分类名
//会话框状态
const isArticlePublishEditorShow = ref(false)
// 发布文章表单引用
const publishArticleFormRef = ref(null)

// 表单对象
const form = reactive({
    id: null,
    title: '',
    content: '请输入内容',
    cover: '',
    categoryId: null,
    tags: [],
    summary: ""
})

// 表单校验规则
const rules = {
    title: [
        { required: true, message: '请输入文章标题', trigger: 'blur' },
        { min: 1, max: 52, message: '文章标题要求大于1个字符，小于52个字符', trigger: 'blur' },
    ],
    content: [{ required: true }],
    cover: [{ required: true }],
    categoryId: [{ required: true, message: '请选择文章分类', trigger: 'blur' }],
    tags: [{ required: true, message: '请选择文章标签', trigger: 'blur' }],
}

// 上传封面
function handleCoverChange(file) {
    // 表单对象
    let formData = new FormData()
    // 添加file字段
    formData.append('file', file.raw)
    // 上传图片
    uploadFile(formData).then((res) => {
        if (res.success == true) {
            // 图片上传成功
            form.cover = res.data.url
            showMessage("文章封面上传成功！")
        } else {
            let message = res.message
            showMessage("message", 'error')
        } 

    }).catch((error) => {
     showMessage("图片上传失败！", "error") 
    })
}

// 上传md编辑器中的图片
const onUploadImg = async (files, callback) => {
    const res = await Promise.all(
        files.map((file) => {
            return new Promise((rev, rej) => {
                console.log("markdown 编辑器开始上传文件")
                let formData = new FormData()
                formData.append('file', file)
                uploadFile(formData).then((res) => {
                    console.log(res)
                    console.log("访问路径：" + res.data.url)
                    // 通过callback函数，显示上传图片
                    callback([res.data.url])
                })
            })
        })
    )
}

const categories = ref([])

// 获取分类列表
const getCategories = () => {
    getCategoryList().then((res) => {
        if (res.success == true) {
            categories.value = res.data
        } else {
            showMessage("分类专栏列表获取异常", "error")
        }
    })
}
// 获取分类列表
getCategories()

const tags = ref([])
//获取标签列表
const getTags = () => {
    getTagSelectList().then((res) => {
        if (res.success == true) {
            tags.value = res.data
        } else {
            showMessage("标签列表获取异常", "error")
        }
    })
}
getTags()

//模糊查询标签
const tagSelectLoading = ref(false)
const remoteMethod = (query) => {
    console.log("标签远程搜索：" + tags.value)
    
    if (query) {
        // 显示加载动画
        tagSelectLoading.value = true
        // 构造查询对象
        let params = {"key": query}
        // 调用模糊查询接口
        searchLikeTagName(params).then((res) => {
            if (res.success == true) {
                tags.value = res.data
            }
        }).finally(() => {tagSelectLoading.value = false})
    }
}

// 发布文章
const publishArticleSubmit = () => {
    console.log("提交文章内容" + form.content)
    // 校验表单
    publishArticleFormRef.value.validate((valid) => {
        if (!valid) {
            console.log("文章提交表单格式异常")
            return false
        }

        publishArticle(form).then((res) => {
            if (res.success == true) {
                showMessage("发布成功！")
                router.push("/admin/article/list")
            } else {
                let message = res.message
                showMessage(message, 'error')
            }
        })
    })
}


// 自动保存
const autoSave = () => {
    // 自动保存数据
    autoSaveArticle(form).then((res) => {
        if (res.success == true) {
            showMessage("编辑数据已自动保存！")
            // 设置form参数
            form.title = res.data.detail.title
            form.content = res.data.detail.content
            form.cover = res.data.detail.cover
            form.summary = res.data.detail.summary
            form.categoryId = res.data.detail.categoryId
            form.tags = res.data.detail.tagIds
            form.id = res.data.detail.id
            // 将文章id存入cookie
            setArticleId(form.id)
            // 跳转到编辑文章页面
            router.push("/admin/update/article/edit/" + getArticleId())
        } else {
            let message = res.message
            showMessage(message, 'error')
        }
    })
}

// 获取文章详情
const getArticleDetail = (id) => {
    //获取文章id
    let params = {
        "id": id
    }
    console.log(params)
    // 获取文章详情
    viewArticle(params).then((res) => {
        if (res.success == true) {
            // 设置表单数据
            form.id = res.data.id
            form.title = res.data.title
            form.cover = res.data.cover
            form.content = res.data.content
            form.categoryId = res.data.categoryId
            form.summary = res.data.summary
            form.tags = res.data.tagIds
        } else {
            let message = res.message
            showMessage(message, 'error')
        }
    })
}

// 保存
const onSave = (v, h) => {
    // console.log(v);
    // 保存数据
    autoSave()
    let articleId = getArticleId()
    console.log(articleId)
    //getArticleDetail(articleId)
//   h.then((html) => {
//     console.log(html);
//   });
}

const beforeunloadHandler = (e) => {
    let articleId = getArticleId()
    console.log(articleId)
    getArticleDetail(articleId)
    // 兼容不同浏览器的提示方式
    let confirmationMessage = '您确定要离开吗？';
    e.returnValue = confirmationMessage;  // Gecko, Trident, Chrome 34+
    return confirmationMessage;           // Gecko, WebKit, Chrome <34
}

const unloadHandler = (e) => {
    autoSave()
}

// // 添加页面关闭与页面刷新事件
// onMounted(() => {
//     window.addEventListener("beforeunload", (e) => beforeunloadHandler(e))
//     window.addEventListener("unload", (e) => unloadHandler(e))
// })

// // 页面关闭前，移除监听事件
// onBeforeUnmount(() => {
//     window.removeEventListener("beforeunload", (e) => beforeunloadHandler(e))
//     window.removeEventListener("unload", (e) => unloadHandler(e))
// })

const sleep = (delay) => new Promise((resolve) => setTimeout(resolve, delay))
// 退出编辑框
const exitEdit = () => {
    showModel("确认离开文章编辑吗?", 'warning', '小闻温馨提示', true).then(() => {
        showModel("是否保存所编辑文章?", 'warning', "内容保存提示", true)
        .then(async() => {
            // 自动保存数据
            showMessage("自动保存数据中..., 1s后为您自动跳转...")
            autoSave()
            removeArticleId()
            // 回到文章列表管理页
            await sleep(1000)
            router.push("/admin/article/list")
            await sleep(100)
        })
        .catch(async() => {
            router.push("/admin/article/list")
            await sleep(100)
        })
    })
}
</script>

<style scoped>
/* 封面图片样式 */
.avatar-uploader .avatar {
    width: 200px;
    height: 100px;
    display: block;
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 200px;
    height: 100px;
    text-align: center;
}
/* ::v-deep是vue3提供的深度选择器，.el-form-item__label是element-plus官方定义的类 */
::v-deep .el-form-item__label{
  font-weight: bold;
  font-size: 16px;
}
</style>

<style>
.md-editor-footer {
    height: 40px;
    font-size: 14px;
    font-weight: bolder;
}
</style>